//
//  ZZFNetWorkCore.m
//  zhangzhongfo
//
//  Created by 瞿衡 on 17/2/9.
//  Copyright © 2017年 瞿衡. All rights reserved.
//

#import "BZNetWorkCore.h"
#import <UIKit/UIKit.h>
#import <BZPreHeaderComponent/BZPreHeaderComponent.h>
#import <AFNetworking/AFNetworking.h>
#import "BZResponsePaser.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "BZBaseNetWorkHeader.h"
#import "NSError+NetworkError.h"


//const NSString *test = @"";

@implementation BZNetWorkCore

+ (BOOL)requestByParamSync:(NSDictionary *)param
                       uri:(NSString *)uri
                httpMethod:(NSString *)httpMethod
               headerParam:(NSDictionary *)headerParam
                  outError:(NSError *__autoreleasing *)outError{

    AFNetworkReachabilityManager *networkManager = [AFNetworkReachabilityManager sharedManager];
    if (networkManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        
        
        [SVProgressHUD setMaximumDismissTimeInterval:0.75];
        [SVProgressHUD showWithStatus:@"无网络"];
        if (outError) {
            *outError = [NSError errorWithDomain:@"com.cn.bz"
                                            code:-404
                                        userInfo:@{NSLocalizedDescriptionKey:@"无网络"}];
        }
        return NO;
    }
    
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    manager.requestSerializer      = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer     = [AFJSONResponseSerializer serializer];
    
    AFJSONResponseSerializer *repsonseSerializer = [AFJSONResponseSerializer serializer];
    repsonseSerializer.removesKeysWithNullValues = YES;
    manager.responseSerializer                   = repsonseSerializer;
    
    NSString *urlStrl              = [NSString stringWithFormat:@"%@%@",HTTPHost,uri];
    
    for (NSString *key in [headerParam allKeys]) {
        
        [manager.requestSerializer setValue:[headerParam objectForKey:key]
                         forHTTPHeaderField:key];
    }
    
    
    NSURLSessionDataTask *dataTask = nil;
    
    __block BOOL requestSuccess = NO;
    
    if ([httpMethod isEqualToString:@"GET"]) {
        
        dataTask = [manager GET:urlStrl
                     parameters:param
                       progress:nil
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            [BZResponsePaser handleResponseObject:responseObject
                                                  task:task
                                               success:^(NSString *code, id responseObject) {
                                                   
                                                   requestSuccess = YES;
                                                   dispatch_semaphore_signal(semaphore);

                                               } failure:^(NSString *code, NSError *error) {
                                                   
                                                   requestSuccess = YES;
                                                   dispatch_semaphore_signal(semaphore);
                                               }];
                            
                        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            
                            requestSuccess = NO;
                            if (outError) {
                                *outError = error;
                            }
                            dispatch_semaphore_signal(semaphore);
                        }];
        
    }else if ([httpMethod isEqualToString:@"POST"]){
        
        dataTask = [manager POST:urlStrl
                      parameters:param
                        progress:nil
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                             
                             [BZResponsePaser handleResponseObject:responseObject
                                                   task:task
                                                success:^(NSString *code, id responseObject) {
                                                    
                                                    requestSuccess = YES;
                                                    dispatch_semaphore_signal(semaphore);
                                                    
                                                } failure:^(NSString *code, NSError *error) {
                                                    
                                                    requestSuccess = YES;
                                                    dispatch_semaphore_signal(semaphore);
                                                    
                                                }];
                             
                             
                         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                             
                             requestSuccess = NO;
                             if (outError) {
                                 *outError = error;
                             }
                             requestSuccess = NO;
                             dispatch_semaphore_signal(semaphore);
                             
                         }];
    }
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    return requestSuccess;
}

+ (void)requestByParam:(NSDictionary *)param
                   uri:(NSString *)uri
            httpMethod:(NSString *)httpMethod
           headerParam:(NSDictionary *)headerParam
               success:(void(^)(NSString *code , id responseObject))success
               failure:(void(^)(NSString *code,NSError *error))failure{
    
    AFNetworkReachabilityManager *networkManager = [AFNetworkReachabilityManager sharedManager];
    if (networkManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        
        
//        [MBProgressHUD showClueInView:[UIApplication sharedApplication].keyWindow title:@"无网络" duration:0.75];
//        ZZFLog(@"无网络");
        if (failure) {
            NSError *error = [NSError errorWithDomain:@"com.cn.zzf"
                                                 code:-404
                                             userInfo:@{NSLocalizedDescriptionKey:@"无网络"}];
            failure(@"网络错误!",error);
        }
        return;
    }
    
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    manager.requestSerializer      = [AFJSONRequestSerializer serializer];
    manager.responseSerializer     = [AFJSONResponseSerializer serializer];
    NSString *urlStrl              = [NSString stringWithFormat:@"%@%@",HTTPHost,uri];
    
    for (NSString *key in [headerParam allKeys]) {
        
        [manager.requestSerializer setValue:[headerParam objectForKey:key]
                         forHTTPHeaderField:key];
    }

    
    NSURLSessionDataTask *dataTask = nil;
    
    if ([httpMethod isEqualToString:@"GET"]) {
        
        dataTask = [manager GET:urlStrl
                     parameters:param
                       progress:nil
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            [BZResponsePaser handleResponseObject:responseObject
                                                  task:task
                                               success:success
                                               failure:failure];
                       
                        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            
                            if (failure) {
                                failure(nil,error);
                            }
                        }];
        
    }else if ([httpMethod isEqualToString:@"POST"]){
        
       dataTask = [manager POST:urlStrl
                     parameters:param
                       progress:nil
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                          
                            [BZResponsePaser handleResponseObject:responseObject
                                                  task:task
                                               success:success
                                               failure:failure];
                            
                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                              
                              if (failure) {
                                  failure(nil,error);
                              }
                     }];
    }
}




@end
